package com.yxjx.duoxue.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.concurrent.Executors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.tencent.stat.MtaSDkException;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.R.layout;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMActivity;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.DMLocationPoints;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class ActivitiesPageFragment extends Fragment implements
		OnRefreshListener, OnLoadListener {
	
	public static final int PAGE_ACTIVITY_NUM = 5;
	// cache rootview;
	private View rootView;
	// sort by
	private int mSortBy = 0;
	Hashtable<Integer, ArrayList<DMActivity>> tabSearchCache = new Hashtable<Integer, ArrayList<DMActivity>>();
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.fragment_activities_home, null);
			mList = (AutoListView) rootView.findViewById(R.id.list);
			mList.setPageSize(PAGE_ACTIVITY_NUM);
			mAdapter = new ActivitiesAdapter();
			mList.setAdapter(mAdapter);
			mList.setOnRefreshListener(this);
			mList.setOnLoadListener(this);
			mList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					
					if (arg2 >= mAdapter.getCount() + 1 || arg2 == 0) {
						return;
					}
					
					Intent intent = new Intent(ActivitiesPageFragment.this.getActivity(), ActivityIntroductionActivity.class);
					intent.putExtra(Yx.EXTRA_DM_ACTIVITY_ID, mAdapter.getDMActivity(arg2 - 1).getActivityId());
					startActivity(intent);
				}
			});
			
			// 初始化search conditon
			sortByLatest = rootView.findViewById(R.id.sort_by_latest);
			sortByHot = rootView.findViewById(R.id.sort_by_hot);
			sortByNear = rootView.findViewById(R.id.sort_by_near);
			UIHelper.setClickListener(rootView, R.id.sort_by_latest, mClickListener);
			UIHelper.setClickListener(rootView, R.id.sort_by_hot, mClickListener);
			UIHelper.setClickListener(rootView, R.id.sort_by_near, mClickListener);
			selectTab(R.id.sort_by_latest);
			return rootView;
		} else {
			// used the cached one.
			ViewGroup parent = (ViewGroup) rootView.getParent();
			if (parent != null) {
				parent.removeView(rootView);
			}
			return rootView;
		}
		
	}

	private void requestActvitityList() {
		final JSONObject params = new JSONObject();
		
		try {
			params.put("area", "0_0");
			params.put("count", "" + PAGE_ACTIVITY_NUM);
			params.put("startindex", "0");
			params.put("order", getOrderBy());
			
			DMBaiduLocation location = DMBaiduLocation.getLocation(getActivity());
			if (location != null) {
				params.put("gps", location.getLatitude() + "," + location.getLongtitude());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		requestActivitiesByParams(params, AutoListView.REFRESH);
	}
	
	private void requestMoreActivities() {
		final JSONObject params = new JSONObject();
		
		try {
			params.put("area", "0_0");
			params.put("count", "" + PAGE_ACTIVITY_NUM);
			params.put("startindex", "" + (mAdapter.getCount() + 1));
			params.put("order", getOrderBy());
			DMBaiduLocation location = DMBaiduLocation.getLocation(getActivity());
			params.put("gps", location.getLatitude() + "," + location.getLongtitude());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		requestActivitiesByParams(params, AutoListView.LOAD);
	}

	private void requestActivitiesByParams(final JSONObject params, final int callbackId) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<DMActivity> activities = new ArrayList<DMActivity>();
				
				try {
					activities = NwUtils.requestDataInfoList(NwUtils.REQ_ACTIVITY_LIST, params, getActivity());
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}

				mHandler.sendMessage(mHandler.obtainMessage(callbackId, activities));
			}
		}).start();
	}
	
	private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(android.os.Message msg) {
    		ArrayList<DMActivity> result = (ArrayList<DMActivity>) msg.obj;
    		switch (msg.what) {
			case AutoListView.REFRESH:
				removeMessages(AutoListView.REFRESH);
				mAdapter.setActivities(result);
				mList.onRefreshComplete();
				// try to progress dialog
				dismissDialog();
				break;
			case AutoListView.LOAD:
				removeMessages(AutoListView.LOAD);
				mAdapter.addActivities(result);
				mList.onLoadComplete();
				break;
			default:
				break;
			}
    		mList.setResultSize(result.size());
    	}
    };
	
	class ActivitiesAdapter extends BaseAdapter {
		
		private ArrayList<DMActivity> mActivities = new ArrayList<DMActivity>();
		
		public DMActivity getDMActivity(int index) {
			return mActivities.get(index);
		}
		
		public void addActivities(ArrayList<DMActivity> items) {
			mActivities.addAll(items);
			tabSearchCache.put(mSortBy, mActivities);
			notifyDataSetChanged();
		}
		
		public void setActivities(ArrayList<DMActivity> items) {
			mActivities = items;
			tabSearchCache.put(mSortBy, mActivities);
			notifyDataSetChanged();
		}
		
		public ArrayList<DMActivity> getActivities() {
			return mActivities;
		}

		@Override
		public int getCount() {
			return mActivities == null ? 0 : mActivities.size();
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getActivity()).inflate(R.layout.item_list_activities_home, null);
			} else {
				ret = arg1;
			}
			DMActivity item = mActivities.get(arg0);
			UIHelper.setText(ret, R.id.title, item.getActivityName());
			UIHelper.setText(ret, R.id.host_by, item.getHostName());
			UIHelper.asyncLoadRoundImage((ImageView) ret.findViewById(R.id.image), item.getHeadImageUrl(), R.drawable.default_banner);
			UIHelper.setText(ret, R.id.time, Utils.getTimeDuration(item.getStartTime(), item.getEndTime()));
//			UIHelper.setText(ret, R.id.remdind_num, Utils.getRemindTime(item.getEndTime()));
			UIHelper.setText(ret, R.id.remdind_num, item.getLeftDays());
			UIHelper.setText(ret, R.id.distance, Utils.getDistanceDesc(getActivity(), item.getSchoolGps()));
			UIHelper.setText(ret, R.id.visit_num, Utils.getCount(item.getVisitedCount()));
			DMLocationPoints addrList = item.getAddrList();
			String addr = "线上活动";
			if (addrList == null || addrList.getList() == null || addrList.getList().size() == 0) {
				addr = "线上活动";
				UIHelper.setText(ret, R.id.distance, "");
			} else if (addrList.getList().size() > 1) {
				addr = "多商圈";
				UIHelper.setText(ret, R.id.distance, "");
			} else {
				addr = addrList.getList().get(0).getAddress();
			}
			UIHelper.setText(ret, R.id.host_by, addr);
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

	}
	
	class LoadingAsyncTask extends AsyncTask<String, Integer, ArrayList<DMActivity>> {

		@Override
		protected ArrayList<DMActivity> doInBackground(String... arg0) {
			ArrayList<DMActivity> activities = new ArrayList<DMActivity>();
			
			try {
				activities = NwUtils.requestDataInfoList(arg0[0], getActivity());
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return activities;
		}
		
		@Override
		protected void onPostExecute(ArrayList<DMActivity> result) {
			super.onPostExecute(result);
			mAdapter.setActivities(result);
		}
		
	}
	
	private void dismissDialog() {
		rootView.findViewById(R.id.loading).setVisibility(View.INVISIBLE);
		rootView.findViewById(R.id.root).setVisibility(View.VISIBLE);
	}
	
	private void showDialog() {
		rootView.findViewById(R.id.loading).setVisibility(View.VISIBLE);
		rootView.findViewById(R.id.root).setVisibility(View.INVISIBLE);
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.sort_by_latest:
			case R.id.sort_by_hot:
			case R.id.sort_by_near:
				selectTab(arg0.getId());
				break;
			default:
				break;
			}
		}
	};

	private void selectTab(int id) {
		switch (id) {
		case R.id.sort_by_latest:
			sortByLatest.setSelected(true);
			sortByHot.setSelected(false);
			sortByNear.setSelected(false);
			break;
		case R.id.sort_by_hot:
			sortByLatest.setSelected(false);
			sortByHot.setSelected(true);
			sortByNear.setSelected(false);
			break;
		case R.id.sort_by_near:
			sortByLatest.setSelected(false);
			sortByHot.setSelected(false);
			sortByNear.setSelected(true);
			break;
		default:
			break;
		}
		if (mSortBy == id) {
			// do nothing
		} else {
			mSortBy = id;
			// use cache
			if (tabSearchCache.containsKey(mSortBy)) {
				mAdapter.setActivities(tabSearchCache.get(mSortBy));
				if (mAdapter.getCount() > 0) {
					mList.setSelection(0);
				}
				dismissDialog();
			} else {
				showDialog();
				if (mAdapter.getCount() > 0) {
					mList.setSelection(0);
				}
				requestActvitityList();
			}
		}
	}
	
	private int getOrderBy() {
		//排序order说明：0默认,1最新,2热门,3最近
		int ret = 0;
		switch (mSortBy) {
		case R.id.sort_by_latest:
			ret = 1;
			break;
		case R.id.sort_by_hot:
			ret = 2;
			break;
		case R.id.sort_by_near:
			ret = 3;
			break;
		}
		return ret;
	}
	private ActivitiesAdapter mAdapter;
	private AutoListView mList;
	private View sortByLatest;
	private View sortByHot;
	private View sortByNear;
	
	/// for Refresh and loading more - Start
	@Override
	public void onLoad() {
		requestMoreActivities();
	}

	@Override
	public void onRefresh() {
		requestActvitityList();
	}

}
